import qs from 'querystringify';
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import request from '../../utils/fetch';
import Carousel from './Carousel';
import NewsTabs from './NewsTabs'
import Page from '../../components/Page';

export default class NewsList extends Component {
  constructor(props) {
    super(props)
    let query = this.getQuery(props.location.search),
    cid = +query.cid || 0,
    page = +query.page || 1
    this.state = {
      cid,
      page,
      page_size: 4,
      pages: 0,
      classify: [],
      banner: [],
      hots: [],
      articles: []
    }
  }
  getQuery(search) {
    return qs.parse(search)
  }
  componentDidMount() {
    this.getClassify().then(res => {
      let cid = 0
      if (!this.state.cid && res.data[0]) {
        cid = res.data[0].id
        this.setState({
          cid
        })
      }
      this.setState({
        classify: res.data
      })
      return cid
    }).then(this.getMain.bind(this))
  }
  componentWillReceiveProps(nextProps) {
    const query = this.getQuery(nextProps.location.search)
    let cid = +query.cid || 0,
    page = +query.page || 1
    this.setState({
      cid,
      page,
      banner: [],
      host: [],
      articles: []
    }, this.getMain)
  }
  getClassify() {
    return request.get(`/web/classify/getClassifyByPid?pid=1`).catch(err => {
      console.log(err)
    })
  }
  getMain() {
    Promise.all([this.getBanner(), this.getHots(), this.getArticles()]).then(([res1, res2, res3]) => {
      const hots = res2.data.data.map(item => {
        let date = new Date(item.public_time.replace(/\-/g, '/'));
        item.year = date && date.getFullYear();
        item.month = date && (1 + date.getMonth() + '/' + date.getDate());
        return item
      }),
      articles = res3.data.data.map(item => {
        let date = new Date(item.public_time.replace(/\-/g, '/'));
        item.year = date && date.getFullYear();
        item.month = date && (1 + date.getMonth() + '/' + date.getDate());
        item.content_mini = item.content_mini.replace(/<\/?.+?>/g, '').replace(/ /g, '');
        if (item.hits_compute > 99999999) {
          item.hits_compute = (item.hits_compute / 100000000).toFixed(1) + 'y';
        } else if (item.hits_compute > 9999) {
          item.hits_compute = (item.hits_compute / 10000).toFixed(1) + 'w';
        }
        return item;
      })
      this.setState({
        banner: res1.data.data,
        hots,
        articles,
        pages: Math.ceil(res3.data.count / this.state.page_size)
      })
    }).catch(err => {
      console.log(err)
    })
  }
  getBanner() {
    return request.get(`/web/Article/getArticleList?model=1&page=${this.state.page}&page_size=5`).catch(err => {
      console.log(err)
    })
  }
  getHots() {
    return request.get(`/web/Article/getArticleList?cid=${this.state.cid}&model=2&page=${this.state.page}&page_size=3`).catch(err => {
      console.log(err)
    })
  }
  getArticles() {
    return request.get(`/web/Article/getArticleList?cid=${this.state.cid}&model=3&page=${this.state.page}&page_size=${this.state.page_size}`).catch(err => {
      console.log(err)
    })
  }
  toPage(page) {
    this.setState({
      page
    })
    this.getMain()
  }
  render() {
    const pathname = this.props.location.pathname,
    search = this.getQuery(this.props.location.search),
    banner = this.state.banner
    return (
      <div>
        <Carousel banner={banner}></Carousel>
        <div className="container">
          <NewsTabs search={search} classify={this.state.classify} cid={this.state.cid}></NewsTabs>
          {
            this.state.hots.length ? 
              <ul className="row mt-5 text">

              </ul> : 
              null
          }
          <ul className="section-news-list row mt-5">
            {
              this.state.articles.length ? this.state.articles.map((item, i) => (
                <li className="w-100 my-4" key={i}>
                  <Link to={`${pathname}/${item.id}`} className="d-flex">
                    <div className="section-news-date text-center">
                      <div className="h3">{item.month}</div>
                      <div>{item.year}</div>
                    </div>
                    <div className="section-news-img ml-4">
                      <img src={item.cover_img || 'http://ouf12p6vg.bkt.clouddn.com/WechatIMG185-400%2A400.png'} alt=""/>
                    </div>
                    <div className="section-news-intro col pr-4">
                      <div className="row">
                        <div className="title col mt-1 mr-5 font-weight-bold">{item.title}</div>
                        <div className="col-auto">阅读量：<span className="color-theme">{item.hits_compute}</span></div>
                      </div>
                      <div className="mt-4 text-truncate">{item.content_mini}</div>
                    </div>
                  </Link>
                </li>
              )) : null
            }
          </ul>
          {
            this.state.pages > 1 ? (
              <Page pathname={pathname} search={search} page={this.state.page} pages={this.state.pages}></Page>
            ) : null
          }
        </div>
      </div>
    )
  }
}
